/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.app.util.locator.factory;

import kz.kstu.ent.app.util.locator.EJBLocalServiceLocator;
import kz.kstu.ent.app.util.locator.EJBRemoteServiceLocator;
import kz.kstu.ent.app.util.locator.ServiceLocator;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Oleg Anastassov
 *         created: 8/5/11 2:40 PM
 */
public final class ServiceLocatorFactory {

    private static final Map<String, ServiceLocator> SERVICE_LOCATOR_CACHE = new HashMap<String, ServiceLocator>();

    private ServiceLocatorFactory() {
    }

    public static ServiceLocator getServiceLocator(boolean isOnline) {
        String className = isOnline ? EJBRemoteServiceLocator.class.getName() :
                EJBLocalServiceLocator.class.getName();
        ServiceLocator serviceLocator;
        if (SERVICE_LOCATOR_CACHE.containsKey(className)) {
            serviceLocator = SERVICE_LOCATOR_CACHE.get(className);
        } else {
            try {
                Class<ServiceLocator> serviceClass = (Class<ServiceLocator>) Class.forName(className);
                serviceLocator = serviceClass.newInstance();
                SERVICE_LOCATOR_CACHE.put(className, serviceLocator);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Error during getting service locator: " + className, e);
            } catch (InstantiationException e) {
                throw new IllegalArgumentException("Error during getting instance of service locator: " + className, e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException("Error during getting instance of service locator: " + className, e);
            }
        }
        return serviceLocator;
    }
}
